﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ApplicationGenerator.GeneratorMenu.BusinessLogic;

namespace ApplicationGenerator.CommonWeb
{
    /// <summary>
    /// Klasa bazowa dla stron z menu i kontrolką do walidacji
    /// </summary>
    public class BasePage : Page
    {
        private Panel _errorPanel;
        private HtmlForm _mainForm;

        protected override void OnPreInit(EventArgs e)
        {
            if (!SearchControl(this))
            {
                throw new Exception("Nie można znaleźć kontrolki formularza");
            }

            _errorPanel = new Panel();
            _mainForm.Controls.AddAt(0, _errorPanel);

            InitializeMenu();
            AddWebPageToHistory();

            base.OnPreInit(e);
        }

        private void InitializeMenu()
        {
            System.Web.UI.WebControls.Menu menu = (new MenuConfiguration()).GetMenu(User.Identity.Name);
            menu.Orientation = Orientation.Horizontal;
            menu.StaticEnableDefaultPopOutImage = false;
            _mainForm.Controls.AddAt(0, menu);
        }

        private bool SearchControl(Control control)
        {
            foreach (var searchControl in control.Controls)
            {
                if (searchControl is HtmlForm)
                {
                    _mainForm = searchControl as HtmlForm;
                    return true;
                }

                if (SearchControl(searchControl as Control))
                {
                    return true;
                }
            }

            return false;
        }

        public void AddErrorMessage(string strErrorMessage)
        {
            Panel newPanel = new Panel();
            Literal literal = new Literal();
            literal.Text = strErrorMessage;
            newPanel.Controls.Add(literal);
            _errorPanel.Controls.Add(newPanel);
        }

        /// <summary>
        /// Dodaje stronę do historii
        /// </summary>
        private void AddWebPageToHistory()
        {
            WebPagesHistory webPagesHistory = Session[WebPagesHistory.HistorySessionKeyName] as WebPagesHistory;
            if (webPagesHistory == null)
            {
                webPagesHistory = new WebPagesHistory();
                Session[WebPagesHistory.HistorySessionKeyName] = webPagesHistory;
            }

            webPagesHistory.AddToHistory(this.Page.Request.Url.PathAndQuery, this.Page.Request.QueryString);
        }
    }
}
